package com.sen.service.impl;

import com.sen.config.security.JwtTokenUtil;
import com.sen.config.security.MyUserDetailService;
import com.sen.entity.Account;
import com.sen.entity.Resource;
import com.sen.result.Result;
import com.sen.service.AccountService;
import com.sen.service.LoginService;
import com.sen.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private MyUserDetailService userDetailService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private ResourceService resourceService;

    //token的头部信息
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
     * 登录验证
     * @param username
     * @param password
     * @return
     */
    @Override
    public Result login(String username, String password) {
        UserDetails userDetails = userDetailService.loadUserByUsername(username);
        if (ObjectUtils.isEmpty(userDetails)){
            return Result.error().msg("用户名不存在");
        }
        if (!passwordEncoder.matches(password, userDetails.getPassword())){
            return Result.error().msg("密码错误");
        }
        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(userDetails,null, userDetails.getAuthorities());
        //将用户登录信息放入security上下文对象中
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String,Object> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        return Result.ok().msg("登录成功").data("data", tokenMap);
    }
}
